#!/usr/bin/env python
#MIME attachment generation

from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import Utils, Encoders
import mimetypes, sys

def attachment(filename):
    fd = open(filename, 'rb')
    mimetype, mimeendcoding = mimetypes.guess_type(filename)
    if mimeendcoding or (mimetype is None):
        mimetype = 'application/octet-stream'

    mimetype, subtye = mimetype.split('/')

    if mimetype == 'text':
        retval = MIMEText(fd.read(), _subtype=subtye)
    else:
        retval = MIMEBase(mimetype, subtye)
        retval.set_payload(fd.read())
        Encoders.encode_base64(retval)

    retval.add_header('Content-Disposition', 'attachment', filename=filename)
    fd.close()

    return retval


message = """Hello,
This is a test messgae from Chapter9 I hope you enjoy it!
-- Anonymous
"""

msg = MIMEMultipart()

msg['To'] = 'evenvi@126.com'
msg['From'] = 'Evenvi <evenvi@163.com>'
msg['Subject'] = 'Test Message, Chapter 9'
msg['Data'] = Utils.formatdate(localtime=1)
msg['Message-ID'] = Utils.make_msgid()

body = MIMEText(message, _subtype='plain')
msg.attach(body)

for filename in sys.argv[1:]:
    msg.attach(attachment(filename))

print msg.as_string()
